import { Transaction } from "tiny-entity2";
import { IQueryObject } from "tiny-entity2/queryObject";
import { ServiceException } from "../common/excpetion";
import { ApiDataContext } from "../domain/apiDataContext";
import { AccountRoles } from "../domain/models/accountRoles";
import { BaseService } from "./baseService";

export class AccountRolesService extends BaseService {
    async CreateAccountRoles(entity: AccountRoles, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new AccountRoles();
            d.ConverToEntity(entity);
            return ctx.Create(d);
        });
    }
    async UpdateAccountRoles(entity: AccountRoles, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new AccountRoles();
            d.ConverToEntity(entity);
            return ctx.Create(d);
        });
    }
    async DeleteAccountRoles(entity: AccountRoles, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new AccountRoles();
            d.ConverToEntity(entity);
            if(d.id)
            {
                return ctx.Delete(d);
            }
            else if(d.accountId && d.roleId)
            {
                return ctx.Delete<AccountRoles>(x=>x.accountId == $args1 && x.roleId==$args2, ctx.AccountRoles,{$args1:d.accountId,$args2:d.roleId});
            }
            else if(d.accountId)
            {
                return ctx.Delete<AccountRoles>(x=>x.accountId == $args1, ctx.AccountRoles,{$args1:d.accountId});
            }
            else if(d.roleId)
            {
                return ctx.Delete<AccountRoles>(x=>x.roleId == $args1, ctx.AccountRoles,{$args1:d.roleId});
            }
            else
            {
                throw new ServiceException("删除的参数不能为空","not_be_null");          
            }
        });
    }
    async GetAccountRolesById(id: string) {
        let ctx = new ApiDataContext();
        return ctx.AccountRoles.First(x => x.id == $args1, { $args1: id });
    }
    async QueryAccountRoles(params) {
        let ctx = new ApiDataContext();
        let q = ctx.AccountRoles as IQueryObject<AccountRoles>;
        if (params) {
            if (params.accountId) {
                q = q.Where(x => x.accountId == $args1, { $args1: params.accountId });
            }
            if (params.roleId) {
                q = q.Where(x => x.roleId == $args1, { $args1: params.roleId });
            }
        }
        let list = await q.ToList();

        return list;
    }
}